package top.ezzz.esclient

import cn.hutool.core.io.FileUtil
import cn.hutool.core.net.NetUtil
import cn.hutool.core.util.ReUtil
import cn.hutool.core.util.ZipUtil
import cn.hutool.http.HttpUtil
import com.intellij.ui.jcef.JBCefBrowser
import java.awt.BorderLayout
import javax.swing.BorderFactory
import javax.swing.JPanel

class CalendarToolWindowContent {
    val contentPanel = JPanel()

    // 创建 JBCefBrowser
    private val browser = JBCefBrowser()

    init {
        contentPanel.layout = BorderLayout(0, 20)
        contentPanel.border = BorderFactory.createEmptyBorder(1, 0, 0, 0)
        // 将 JBCefBrowser 的UI控件设置到Panel中
        contentPanel.add(browser.component, BorderLayout.CENTER)
        // 创建 http服务
        var libPath = "."
        var uri = this.javaClass.classLoader.getResource("index.html")?.path
        if (uri != null) {
            uri = uri.removePrefix("file:/")
            libPath = ReUtil.get("(.+)lib", uri, 0)
            if (!FileUtil.exist(libPath + "/html")) {
                ZipUtil.unzip(ReUtil.get("(.+)jar", uri, 0), libPath + "/html")
                FileUtil.del(libPath + "/html/META-INF")
                FileUtil.del(libPath + "/html/top")
            }
            println("$libPath/html/esclint")
        }
        var port = 18080
        while (true) {
            val usableLocalPort = NetUtil.isUsableLocalPort(port)
            if (usableLocalPort) {
                break
            }
            port++
        }
        HttpUtil.createServer(port)
                // 设置默认根目录
                .setRoot(libPath + "/html/esclint")
                .start();
        // 加载URL
        browser.loadURL("http://localhost:$port/index.html")
    }
}